package com.kakarote.hrm.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.BigExcelWriter;
import cn.hutool.poi.excel.ExcelUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.excel.EasyExcel;
import com.kakarote.common.log.entity.OperationLog;
import com.kakarote.common.log.enums.BehaviorEnum;
import com.kakarote.core.common.MultipartFileUtil;
import com.kakarote.core.common.Result;
import com.kakarote.core.common.cache.AdminCacheKey;
import com.kakarote.core.common.cache.HrmCacheKey;
import com.kakarote.core.common.enums.FieldEnum;
import com.kakarote.core.common.enums.SystemCodeEnum;
import com.kakarote.core.entity.BasePage;
import com.kakarote.core.entity.UploadEntity;
import com.kakarote.core.exception.CrmException;
import com.kakarote.core.feign.admin.service.AdminFileService;
import com.kakarote.core.redis.Redis;
import com.kakarote.core.servlet.BaseServiceImpl;
import com.kakarote.core.utils.ExcelParseUtil;
import com.kakarote.hrm.entity.BO.QueryRecruitPlanRecordPageListBO;
import com.kakarote.hrm.entity.PO.HrmRecruitPlan;
import com.kakarote.hrm.entity.PO.HrmRecruitPlanRecord;
import com.kakarote.hrm.entity.VO.RecruitPlanRecordExportVO;
import com.kakarote.hrm.entity.VO.RecruitPlanRecordVO;
import com.kakarote.hrm.entity.VO.RecruitPlanVO;
import com.kakarote.hrm.mapper.HrmRecruitPlanRecordMapper;
import com.kakarote.hrm.service.IHrmRecruitPlanRecordService;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 计划招聘记录 服务实现类
 * </p>
 *
 * @author system
 * @since 2024-01-01
 */
@Service
public class HrmRecruitPlanRecordServiceImpl extends BaseServiceImpl<HrmRecruitPlanRecordMapper, HrmRecruitPlanRecord> implements IHrmRecruitPlanRecordService {

    @Autowired
    private HrmRecruitPlanRecordMapper recruitPlanRecordMapper;
    @Autowired
    private HrmRecruitPlanServiceImpl hrmRecruitPlanService;
    @Autowired
    private Redis redis;
    @Resource
    private AdminFileService adminFileService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public OperationLog addRecruitPlanRecord(HrmRecruitPlanRecord recruitPlanRecord) {
        RecruitPlanVO recruitPlanVO = hrmRecruitPlanService.queryById(recruitPlanRecord.getPlanId());
        if (recruitPlanVO == null) {
            throw new CrmException(SystemCodeEnum.SYSTEM_ERROR.getCode(), "计划不存在");
        }
        // 生成计划招聘记录编号
        if (StrUtil.isEmpty(recruitPlanRecord.getRecordCode())) {
            recruitPlanRecord.setRecordCode(generateRecruitPlanRecordCode(recruitPlanVO.getPlanId(), recruitPlanVO.getPlanCode()));
        }
        save(recruitPlanRecord);

        OperationLog operationLog = new OperationLog();
        operationLog.setOperationObject(recruitPlanRecord.getRecordId(), "计划招聘记录");
        String detail = String.format("记录名称：%s，记录编号：%s，计划编号：%s，开始日期：%s，结束日期：%s",
                StrUtil.isNotEmpty(recruitPlanRecord.getRecordName()) ? recruitPlanRecord.getRecordName() : "无",
                StrUtil.isNotEmpty(recruitPlanRecord.getRecordCode()) ? recruitPlanRecord.getRecordCode() : "无",
                recruitPlanRecord.getPlanId() != null ? recruitPlanRecord.getPlanId().toString() : "无",
                recruitPlanRecord.getStartDate() != null ? recruitPlanRecord.getStartDate().toString() : "无",
                recruitPlanRecord.getEndDate() != null ? recruitPlanRecord.getEndDate().toString() : "无");
        operationLog.setOperationInfo(detail);
        operationLog.setBehavior(BehaviorEnum.SAVE);
        return operationLog;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public OperationLog setRecruitPlanRecord(HrmRecruitPlanRecord recruitPlanRecord) {
        HrmRecruitPlanRecord oldRecord = getById(recruitPlanRecord.getRecordId());
        if (oldRecord == null) {
            throw new CrmException(SystemCodeEnum.SYSTEM_ERROR.getCode(), "计划招聘记录不存在");
        }

        // 记录变更内容
        StringBuilder detail = new StringBuilder();
        if (!Objects.equals(oldRecord.getRecordName(), recruitPlanRecord.getRecordName())) {
            detail.append(String.format("记录名称：%s → %s；",
                    StrUtil.isNotEmpty(oldRecord.getRecordName()) ? oldRecord.getRecordName() : "无",
                    StrUtil.isNotEmpty(recruitPlanRecord.getRecordName()) ? recruitPlanRecord.getRecordName() : "无"));
        }
        if (!Objects.equals(oldRecord.getRecordCode(), recruitPlanRecord.getRecordCode())) {
            detail.append(String.format("记录编号：%s → %s；",
                    StrUtil.isNotEmpty(oldRecord.getRecordCode()) ? oldRecord.getRecordCode() : "无",
                    StrUtil.isNotEmpty(recruitPlanRecord.getRecordCode()) ? recruitPlanRecord.getRecordCode() : "无"));
        }
        if (!Objects.equals(oldRecord.getPlanId(), recruitPlanRecord.getPlanId())) {
            detail.append(String.format("计划编号：%s → %s；",
                    oldRecord.getPlanId() != null ? oldRecord.getPlanId().toString() : "无",
                    recruitPlanRecord.getPlanId() != null ? recruitPlanRecord.getPlanId().toString() : "无"));
        }
        if (!Objects.equals(oldRecord.getStartDate(), recruitPlanRecord.getStartDate())) {
            detail.append(String.format("开始日期：%s → %s；",
                    oldRecord.getStartDate() != null ? oldRecord.getStartDate().toString() : "无",
                    recruitPlanRecord.getStartDate() != null ? recruitPlanRecord.getStartDate().toString() : "无"));
        }
        if (!Objects.equals(oldRecord.getEndDate(), recruitPlanRecord.getEndDate())) {
            detail.append(String.format("结束日期：%s → %s；",
                    oldRecord.getEndDate() != null ? oldRecord.getEndDate().toString() : "无",
                    recruitPlanRecord.getEndDate() != null ? recruitPlanRecord.getEndDate().toString() : "无"));
        }

        updateById(recruitPlanRecord);

        OperationLog operationLog = new OperationLog();
        operationLog.setOperationObject(recruitPlanRecord.getRecordId(), "计划招聘记录");
        operationLog.setOperationInfo(detail.toString());
        operationLog.setBehavior(BehaviorEnum.UPDATE);
        return operationLog;
    }

    @Override
    public RecruitPlanRecordVO queryById(Long recordId) {
        return recruitPlanRecordMapper.queryById(recordId);
    }

    @Override
    public BasePage<RecruitPlanRecordVO> queryRecruitPlanRecordPageList(QueryRecruitPlanRecordPageListBO queryRecruitPlanRecordPageListBO) {
        BasePage<RecruitPlanRecordVO> page = queryRecruitPlanRecordPageListBO.parse();
        return recruitPlanRecordMapper.queryRecruitPlanRecordPageList(page, queryRecruitPlanRecordPageListBO);
    }

    @Override
    public List<RecruitPlanRecordVO> queryByPlanId(Long planId) {
        return recruitPlanRecordMapper.queryByPlanId(planId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public OperationLog deleteRecruitPlanRecord(Long recordId) {
        HrmRecruitPlanRecord record = getById(recordId);
        if (record == null) {
            throw new CrmException(SystemCodeEnum.SYSTEM_ERROR.getCode(), "计划招聘记录不存在");
        }

        removeById(recordId);
        OperationLog operationLog = new OperationLog();
        operationLog.setOperationObject(recordId, "计划招聘记录");
        operationLog.setOperationInfo(String.format("删除计划招聘记录，记录名称：%s，记录编号：%s，计划编号：%s",
                StrUtil.isNotEmpty(record.getRecordName()) ? record.getRecordName() : "无",
                StrUtil.isNotEmpty(record.getRecordCode()) ? record.getRecordCode() : "无",
                record.getPlanId() != null ? record.getPlanId().toString() : "无"));
        operationLog.setBehavior(BehaviorEnum.DELETE);
        return operationLog;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public OperationLog batchDeleteRecruitPlanRecord(List<Long> recordIds) {
        if (recordIds == null || recordIds.isEmpty()) {
            throw new CrmException(SystemCodeEnum.SYSTEM_ERROR.getCode(), "请选择要删除的记录");
        }

        List<HrmRecruitPlanRecord> records = listByIds(recordIds);
        if (records.isEmpty()) {
            throw new CrmException(SystemCodeEnum.SYSTEM_ERROR.getCode(), "选择的记录不存在");
        }

        removeByIds(recordIds);
        OperationLog operationLog = new OperationLog();
        operationLog.setOperationObject(recordIds.toString(), "批量删除计划招聘记录");
        StringBuilder detail = new StringBuilder("删除记录：");
        for (HrmRecruitPlanRecord record : records) {
            detail.append("记录ID:").append(record.getRecordId());
            if (StrUtil.isNotEmpty(record.getRecordName())) {
                detail.append("(名称:").append(record.getRecordName()).append(")");
            }
            detail.append("、");
        }
        if (detail.length() > 0) {
            detail.setLength(detail.length() - 1);
        }
        operationLog.setOperationInfo(detail.toString());
        operationLog.setBehavior(BehaviorEnum.DELETE);
        return operationLog;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public OperationLog deleteByPlanId(Long planId) {
        Map<String, Object> params = new HashMap<>();
        params.put("plan_id", planId);
        List<HrmRecruitPlanRecord> records = listByMap(params);
        if (!records.isEmpty()) {
            recruitPlanRecordMapper.deleteByPlanId(planId);
        }

        OperationLog operationLog = new OperationLog();
        operationLog.setOperationObject(planId, "删除计划下所有记录");
        operationLog.setOperationInfo(String.format("删除计划下所有记录，共%d个", records.size()));
        operationLog.setBehavior(BehaviorEnum.DELETE);
        return operationLog;
    }

    @Override
    public void exportRecruitPlanRecord(HttpServletResponse response, QueryRecruitPlanRecordPageListBO queryRecruitPlanRecordPageListBO) throws IOException {
        // 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = "计划招聘记录_" + DateUtil.format(new Date(), "yyyyMMddHHmmss") + ".xlsx";
        response.setHeader("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode(fileName, "UTF-8"));

        // 直接查询所有符合条件的数据（不分页）
        List<RecruitPlanRecordVO> dataList = recruitPlanRecordMapper.queryAllRecruitPlanRecordList(queryRecruitPlanRecordPageListBO);

        // 转换为导出VO
        List<RecruitPlanRecordExportVO> exportList = new ArrayList<>();
        for (RecruitPlanRecordVO vo : dataList) {
            RecruitPlanRecordExportVO exportVO = new RecruitPlanRecordExportVO();
            exportVO.setPlanName(vo.getPlanName());
            exportVO.setRecordName(vo.getRecordName());
            exportVO.setRecordCode(vo.getRecordCode());
            exportVO.setStartDate(vo.getStartDate());
            exportVO.setEndDate(vo.getEndDate());
            exportVO.setCreateTime(vo.getCreateTime());
            exportVO.setCreateRealName(vo.getCreateRealName());
            exportList.add(exportVO);
        }

        // 使用EasyExcel导出
        EasyExcel.write(response.getOutputStream(), RecruitPlanRecordExportVO.class)
                .sheet("计划招聘记录")
                .doWrite(exportList);
    }


    @Override
    public void downloadExcel(HttpServletResponse response) {
        List<JSONObject> list = queryField();
        ExcelParseUtil.importExcel(new ExcelParseUtil.ExcelParseService() {
            @Override
            public String getExcelName() {
                return "招聘记录";
            }

            @Override
            public String getMergeContent(String module) {
                return "注意事项：\n" +
                        "1、表头标“*”的红色字体为必填项\n" +
                        "2、导入只新增不修改\n" +
                        "3、计划编号和计划名称必须已存在\n" +
                        "4、日期格式：yyyy-MM-dd，例如：2024-01-01\n" +
                        "5、结束日期必须大于等于开始日期\n";
            }
        }, list, response, "user");
    }

    private List<JSONObject> queryField() {
        List<JSONObject> list = new ArrayList<>();
        list.add(queryField("planName", FieldEnum.TEXT.getFormType(), FieldEnum.TEXT.getType(), "计划名称", 1));
        list.add(queryField("planCode", FieldEnum.TEXT.getFormType(), FieldEnum.TEXT.getType(), "计划编号", 1));
        list.add(queryField("recordName", FieldEnum.TEXT.getFormType(), FieldEnum.TEXT.getType(), "记录名称", 1));
        list.add(queryField("startDate", FieldEnum.DATE.getFormType(), FieldEnum.DATE.getType(), "开始日期", 1));
        list.add(queryField("endDate", FieldEnum.DATE.getFormType(), FieldEnum.DATE.getType(), "结束日期", 1));
        return list;
    }

    private JSONObject queryField(String fieldName, String formType, Integer type, String name, Integer isNull) {
        JSONObject json = new JSONObject();
        json.fluentPut("fieldName", fieldName)
                .fluentPut("formType", formType)
                .fluentPut("type", type)
                .fluentPut("name", name).fluentPut("isNull", isNull);
        return json;
    }

    private String getFilePath(MultipartFile file) {
        String dirPath = FileUtil.getTmpDirPath();
        try {
            InputStream inputStream = file.getInputStream();
            File fromStream = FileUtil.writeFromStream(inputStream, dirPath + "/" + IdUtil.simpleUUID() + file.getOriginalFilename());
            return fromStream.getAbsolutePath();
        } catch (IOException e) {
            throw new CrmException(SystemCodeEnum.SYSTEM_UPLOAD_FILE_ERROR);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public JSONObject excelImport(MultipartFile file) {
        List<List<Object>> errList = new ArrayList<>();
        String filePath = getFilePath(file);
        AtomicReference<Integer> num = new AtomicReference<>(0);
        //新增记录
        List<HrmRecruitPlanRecord> addRecordList = new ArrayList<>();
        //查询所有招聘计划
        List<HrmRecruitPlan> planList = hrmRecruitPlanService.list();
        Map<String, HrmRecruitPlan> planMap;
        if (planList != null && !planList.isEmpty()) {
            planMap = planList.stream().collect(Collectors.toMap(item -> Optional.ofNullable(item.getPlanName()).orElse("") + Optional.ofNullable(item.getPlanCode()).orElse(""), Function.identity(), (v1, v2) -> v1));
        } else {
            planMap = new HashMap<>();
        }

        DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

        ExcelUtil.readBySax(filePath, 0, (int sheetIndex, long rowIndex, List<Object> rowList) -> {
            if (rowIndex > 1) {
                num.getAndSet(num.get() + 1);
                if (rowList.size() < 5) {
                    int size = rowList.size();
                    for (int i = 0; i < 5 - size; i++) {
                        rowList.add("");
                    }
                }
                // 验证必填字段
                if (StrUtil.isEmptyIfStr(rowList.get(0).toString().trim())) {
                    rowList.add(0, "计划名称不能为空");
                    errList.add(rowList);
                    return;
                }
                if (StrUtil.isEmptyIfStr(rowList.get(1).toString().trim())) {
                    rowList.add(0, "计划编号不能为空");
                    errList.add(rowList);
                    return;
                }

                String planKey = rowList.get(0).toString().trim() + rowList.get(1).toString().trim();
                if (!planMap.containsKey(planKey)) {
                    rowList.add(0, "计划不存在");
                    errList.add(rowList);
                    return;
                }

                HrmRecruitPlan plan = planMap.get(planKey);
                if (plan == null) {
                    rowList.add(0, "计划不存在");
                    errList.add(rowList);
                    return;
                }

                if (StrUtil.isEmptyIfStr(rowList.get(2).toString().trim())) {
                    rowList.add(0, "记录名称不能为空");
                    errList.add(rowList);
                    return;
                }
                String recordName = rowList.get(2).toString().trim();

                // 验证开始日期
                LocalDate startDate = null;
                if (StrUtil.isEmptyIfStr(rowList.get(3).toString().trim())) {
                    rowList.add(0, "开始日期不能为空");
                    errList.add(rowList);
                    return;
                }
                try {
                    String startDateStr = rowList.get(3).toString().trim();
                    // 如果包含空格，只取空格前的日期部分
                    if (startDateStr.contains(" ")) {
                        startDateStr = startDateStr.substring(0, startDateStr.indexOf(" "));
                    }
                    startDate = LocalDate.parse(startDateStr, dateFormatter);
                } catch (DateTimeParseException e) {
                    rowList.add(0, "开始日期格式错误，格式应为：yyyy-MM-dd");
                    errList.add(rowList);
                    return;
                }

                // 验证结束日期
                LocalDate endDate = null;
                if (StrUtil.isEmptyIfStr(rowList.get(4).toString().trim())) {
                    rowList.add(0, "结束日期不能为空");
                    errList.add(rowList);
                    return;
                }
                try {
                    String endDateStr = rowList.get(4).toString().trim();
                    // 如果包含空格，只取空格前的日期部分
                    if (endDateStr.contains(" ")) {
                        endDateStr = endDateStr.substring(0, endDateStr.indexOf(" "));
                    }
                    endDate = LocalDate.parse(endDateStr, dateFormatter);
                } catch (DateTimeParseException e) {
                    rowList.add(0, "结束日期格式错误，格式应为：yyyy-MM-dd");
                    errList.add(rowList);
                    return;
                }

                // 验证结束日期必须大于等于开始日期
                if (endDate.isBefore(startDate)) {
                    rowList.add(0, "结束日期必须大于等于开始日期");
                    errList.add(rowList);
                    return;
                }

                HrmRecruitPlanRecord record = new HrmRecruitPlanRecord();
                record.setPlanId(plan.getPlanId());
                record.setRecordCode(generateRecruitPlanRecordCode(plan.getPlanId(), plan.getPlanCode()));
                record.setRecordName(recordName);
                record.setStartDate(startDate);
                record.setEndDate(endDate);
                record.setCreateTime(LocalDateTime.now());
                addRecordList.add(record);
            } else {
                if (rowIndex == 1) {
                    rowList.add(0, "错误信息");
                }
                errList.add(Convert.toInt(rowIndex), rowList);
            }
        });

        if (!addRecordList.isEmpty()) {
            this.saveBatch(addRecordList);
        }
        FileUtil.del(filePath);
        JSONObject result = new JSONObject().fluentPut("totalSize", num.get()).fluentPut("errSize", 0);
        int listSize = 2;
        if (errList.size() > listSize) {
            File errFile = FileUtil.file("excelData/" + IdUtil.simpleUUID() + ".xlsx");
            BigExcelWriter writer = ExcelUtil.getBigWriter(errFile);
            // 取消数据的黑色边框以及数据左对齐
            CellStyle cellStyle = writer.getCellStyle();
            cellStyle.setFillBackgroundColor(IndexedColors.BLACK.getIndex());
            cellStyle.setBorderTop(BorderStyle.NONE);
            cellStyle.setBorderBottom(BorderStyle.NONE);
            cellStyle.setBorderLeft(BorderStyle.NONE);
            cellStyle.setBorderRight(BorderStyle.NONE);
            cellStyle.setAlignment(HorizontalAlignment.LEFT);
            Font defaultFont = writer.createFont();
            defaultFont.setFontHeightInPoints((short) 11);
            cellStyle.setFont(defaultFont);
            // 取消数字格式的数据的黑色边框以及数据左对齐
            CellStyle cellStyleForNumber = writer.getStyleSet().getCellStyleForNumber();
            cellStyleForNumber.setBorderTop(BorderStyle.NONE);
            cellStyleForNumber.setBorderBottom(BorderStyle.NONE);
            cellStyleForNumber.setBorderLeft(BorderStyle.NONE);
            cellStyleForNumber.setBorderRight(BorderStyle.NONE);
            cellStyleForNumber.setAlignment(HorizontalAlignment.LEFT);
            cellStyleForNumber.setFillBackgroundColor(IndexedColors.BLACK.getIndex());
            cellStyleForNumber.setFont(defaultFont);

            CellStyle textStyle = writer.getWorkbook().createCellStyle();
            DataFormat format = writer.getWorkbook().createDataFormat();
            textStyle.setDataFormat(format.getFormat("@"));

            writer.merge(errList.get(1).size() + 1, errList.get(0).get(0).toString().trim(), true);
            writer.getHeadCellStyle().setAlignment(HorizontalAlignment.LEFT);
            writer.getHeadCellStyle().setWrapText(true);
            Font headFont = writer.createFont();
            headFont.setFontHeightInPoints((short) 11);
            writer.getHeadCellStyle().setFont(headFont);
            writer.getHeadCellStyle().setFillPattern(FillPatternType.NO_FILL);
            writer.getOrCreateRow(0).setHeightInPoints(120);
            writer.setRowHeight(-1, 20);

            for (int i = 0; i < errList.get(1).size(); i++) {
                writer.getSheet().setDefaultColumnStyle(i, textStyle);
            }
            errList.remove(0);
            writer.write(errList);
            writer.close();
            //将错误信息的excel保存七天 604800 七天的秒数
            MultipartFile multipartFile = MultipartFileUtil.getMultipartFile(errFile);
            UploadEntity uploadEntity = adminFileService.uploadTempFile(multipartFile, IdUtil.simpleUUID()).getData();

            redis.setex(AdminCacheKey.UPLOAD_EXCEL_MESSAGE_PREFIX + "file:" + uploadEntity.getFileId(), 604800, uploadEntity.getPath());

            result.fluentPut("errSize", errList.size() - 1).fluentPut("token", uploadEntity.getFileId());
        }
        return result;
    }

    @Override
    public UploadEntity uploadTempFile(MultipartFile file, String batchId) {
        Result<UploadEntity> result = adminFileService.uploadTempFile(file, batchId);
        return result.getData();
    }

    /**
     * 生成计划招聘记录编号
     *
     * @return 计划编号
     */
    private String generateRecruitPlanRecordCode(Long planId, String planCode) {
        if (planCode == null || planId == null) {
            return null;
        }
        String key = HrmCacheKey.HRM_RECRUIT_PLAN_RECORD + planId;
        StringBuffer sb = new StringBuffer();
        sb.append("R");
        sb.append(planCode);
        sb.append("_");
        sb.append(String.format("%03d", redis.incr(key)));
        return sb.toString();
    }

}

